// bg.js - Service Worker 版本（修复 CSP 问题）

self.addEventListener('install', (event) => {
  self.skipWaiting(); // 强制激活新 Service Worker
});

self.addEventListener('activate', (event) => {
  event.waitUntil(clients.claim());
});

// 获取爱逛的吧列表
async function getLikeForums() {
  try {
    const response = await fetch('https://tieba.baidu.com/index.html');
    const html = await response.text();

    const reg = /_\.Module\.use\("spage\/widget\/AsideV2[^[]*(\[[^)]+)/;
    const resMatch = html.match(reg);
    const res = resMatch ? resMatch[1] : '[]';

    let arr = [];
    try {
      // 使用 JSON.parse 替代 new Function
      const jsonStr = res
          .replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2":') // 将键名加引号
          .replace(/([\[\{]\s*)?(\d+\.?\d*)(\s*[\}\],]?)/g, '$1"$2"$3'); // 将数字值转为字符串

      arr = JSON.parse(jsonStr);
      return arr[0]?.like_forum || [];
    } catch (e) {
      console.error('解析论坛数据失败', e);
      return [];
    }
  } catch (e) {
    console.error('获取论坛列表失败', e);
    return [];
  }
}

// 获取 tbs
async function getTbs(kw) {
  try {
    const url = `https://tieba.baidu.com/f?ie=utf-8&kw=${encodeURIComponent(kw)}`;
    const response = await fetch(url);
    const text = await response.text();
    const tbsMatch = text.match(/['"]tbs['"]:[\s]*['"]([\w]*)['"]/);
    return tbsMatch ? tbsMatch[1] : null;
  } catch (e) {
    console.error('获取 tbs 失败', e);
    return null;
  }
}

// 执行签到
async function addSign(kw, tbs) {
  try {
    const response = await fetch('https://tieba.baidu.com/sign/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: `ie=utf-8&kw=${encodeURIComponent(kw)}&tbs=${tbs}`
    });
    return await response.json();
  } catch (e) {
    console.error('签到请求失败', e);
    return { error: '请求失败' };
  }
}

// 签到主函数
async function sign(kw) {
  const tbs = await getTbs(kw);
  if (tbs) {
    const result = await addSign(kw, tbs);
    console.log(`签到结果: ${kw}`, result);
  } else {
    console.warn(`无法获取 tbs: ${kw}`);
  }
}

// 批量签到
async function trySign(forums) {
  for (const forum of forums) {
    if (forum.is_sign !== 1) {
      await sign(forum.forum_name);
    }
  }
}

// 初始化签到
async function init() {
  const forums = await getLikeForums();
  const unSignedForums = forums.filter(f => f.is_sign !== 1);
  await trySign(unSignedForums);
}

// 定时任务（每10秒执行一次，用于模拟每日签到）
let lastRunTime = 0;
const ONE_DAY = 24 * 60 * 60 * 1000;

setInterval(async () => {
  const now = Date.now();
  if (now - lastRunTime > ONE_DAY / 24) {
    lastRunTime = now;
    await init();
  }
}, 10000);

// 安装时立即运行一次
init();
